package com.kotle.baselib.mvvm;


import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.ParameterizedType;

/**
 * MVVM fragment的父类
 * T：对应的ViewModel,如果没有，传入默认的BaseViewModel
 * P：根据xml文件生成的ViewDataBinding
 */
public abstract class BaseMvvmFragment<T extends BaseViewModel, P extends ViewDataBinding>
        extends Fragment {
    private P mBinding;//bingding对象
    private T mViewModel;//viewModel对象
    private View mRootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initCreateView(createInflaterView(inflater, container, getLayoutRes()));
        return mRootView;
    }


    /**
     * 在onCreateView的时候调用
     *
     * @param inflater  布局管理器
     * @param container 父view
     * @param layoutRes 资源文件的id
     * @return onCreateView所需要的view
     */
    protected View createInflaterView(LayoutInflater inflater, @Nullable ViewGroup container, int layoutRes) {
        if (mRootView == null) {
            mBinding = DataBindingUtil.inflate(inflater, layoutRes, container, false);
            mRootView = mBinding.getRoot();
            Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            mViewModel = ViewModelProviders.of(this).get(entityClass);
            onObserve(mViewModel);
        }
        return mRootView;
    }

    /**
     * @return xml文件对应的view
     */
    protected View getInflaterView() {
        if (mRootView == null) {
            throw new IllegalArgumentException("获取rootView前，必须先调用至少一次createInflaterView（）");
        }
        return mRootView;
    }

    /**
     * @return 返回binding对象
     */
    protected P getBinding() {
        if (mBinding == null) {
            throw new IllegalArgumentException("使用Binding前，必须先调用至少一次createInflaterView（）");
        }
        return mBinding;
    }

    /**
     * @return viewModel对象
     */
    protected T getViewModel() {
        if (mViewModel == null) {
            throw new IllegalArgumentException("使用ViewModel前，必须先在createViewModel（）返回一个非NULL的对象");
        }
        return mViewModel;
    }
    protected abstract int getLayoutRes();

    protected abstract void initCreateView(View inflateView);

    protected abstract void onObserve(T viewModel);
}
